
<template>
  <div>
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()">
    </van-nav-bar>
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
       @input="hGetSuggestion"
    >
      <template #action>
        <div @click="search">搜索</div>
      </template>
    </van-search>

    <!-- 联想建议区域 -->
    <van-cell-group  v-if="keyword">
      <van-cell  icon="search" v-for=" (item,index) in wrapperList" :key="index">
        <div v-html="item" @click="clickSuggest(index)"></div>
      </van-cell>
      <!-- <van-cell title="jsa" icon="search" /> -->
    </van-cell-group>

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"> </van-cell>
      <van-cell :title="item" v-for="(item,index) in historyList" @click="historyClick(item)" :key="index">
        <van-icon name="close"  @click.stop="delHistory(index)"/>
      </van-cell>
    </van-cell-group>

  </div>
</template>

<script>
import { setHistory, getHistory } from '@/utils/ls.js'
import _ from 'lodash'
import { getSuggestion } from '@/api/search.js'
export default {
  name: 'SearchIndex',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestList: [], // 建议列表
      historyList: getHistory() || []
    }
  },
  computed: {
    // 重点算法
    wrapperList () {
      const newArr = this.suggestList.map(item => {
        const reg = new RegExp(this.keyword, 'gi')
        const newStr = item.replace(reg, (target) => {
          return `<span style="color:red;">${target}</span>`
        })
        return newStr
      })
      return newArr
    }
  },
  methods: {
    historyClick (item) {
      this.$router.push({
        path: '/searchResult',
        query: {
          q: item
        }
      })
    },
    delHistory (index) {
      this.historyList.splice(index, 1)
      setHistory(this.historyList)
    },
    clickSuggest (index) {
      this.historyList.push(this.suggestList[index])
      setHistory(this.historyList)
      this.$router.push({
        path: '/searchResult',
        query: {
          q: this.suggestList[index]
        }
      })
    },
    search () {
      this.$router.push({
        path: '/searchResult',
        query: {
          q: this.keyword
        }
      })
      // 去重
      const a = this.historyList.find(item => {
        return item === this.keyword
      })
      if (a) {
        return
      }
      this.historyList.push(this.keyword)
      setHistory(this.historyList)
    },
    hGetSuggestion: _.debounce(function () {
      if (this.keyword === '') {
        this.suggestList = []
        return false
      }
      getSuggestion(this.keyword).then(res => {
        // console.log(res)
        this.suggestList = res.data.data.options
      })
    }, 400)
  }
}
</script>
<style scoped lang="less">
::v-deep .van-nav-bar .van-icon{
color: #fff;
}
</style>
